<?php

namespace app\admin\service;

use Elasticsearch\ClientBuilder;

class EsService
{


    protected $client;

    public function __construct()
    {
        $es = config("es");
        $this->client = ClientBuilder::create()->setHosts(["{$es}:9200"])->build();
    }

    function addData($id, $content,$dh)
    {
        $data = [
            'id' => $id,
            'content' => $content,
            'dh'=>$dh
        ];
        // 插入数据
        try {
            $response = $this->client->index([
                'index' => 'my_index',
                "type" => "_doc",
                'body' => $data
            ]);

            // 检查响应
            if ($response['result'] === 'created' || $response['result'] === 'updated') {
                return array("code" => 200, "message" => "数据插入成功");
            } else {
                return array("code" => 400, "message" => "数据插入数据库失败");
            }
        } catch (\Exception $e) {


            return array("code" => 400, "message" => $e->getMessage());
        }

        return array("code" => 400, "message" => "数据插入数据库失败");
    }


}